{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# LDA算法\n",
    "from sklearn.datasets import fetch_20newsgroups # 导入20个新闻组数据集\n",
    "from sklearn.feature_extraction.text import CountVectorizer # 文本特征提取\n",
    "from sklearn.decomposition import LatentDirichletAllocation # 导入LDA模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5.00000003e-02 2.86094650e+01 5.00000002e-02 ... 2.50738811e+02\n",
      "  3.39592315e+00 1.07927827e+02]\n",
      " [5.00000006e-02 2.10379953e+01 5.00000001e-02 ... 3.62264958e+01\n",
      "  5.00187721e-02 1.84435950e+01]\n",
      " [5.00000000e-02 5.00000000e-02 5.00000000e-02 ... 5.00000000e-02\n",
      "  5.00000000e-02 5.00000000e-02]\n",
      " ...\n",
      " [5.00000007e-02 9.90762072e+01 9.72355799e+00 ... 1.27427095e-01\n",
      "  3.35496578e+00 5.00000026e-02]\n",
      " [5.00000003e-02 5.00000002e-02 5.00000009e-02 ... 5.41043397e+01\n",
      "  5.00000002e-02 5.00000008e-02]\n",
      " [3.96926993e+00 1.58647209e-01 1.08158726e+01 ... 3.81126610e+01\n",
      "  9.89606146e+00 1.50906110e+01]]\n",
      "[[0.00208333 0.00208333 0.00208333 ... 0.00208333 0.00208333 0.00208333]\n",
      " [0.0025     0.0025     0.0025     ... 0.0025     0.0025     0.0025    ]\n",
      " [0.00060241 0.00060241 0.00060241 ... 0.00060241 0.1568914  0.00060241]\n",
      " ...\n",
      " [0.00454545 0.00454545 0.00454545 ... 0.00454545 0.28862886 0.00454545]\n",
      " [0.00294118 0.00294118 0.00294118 ... 0.13543677 0.00294118 0.00294118]\n",
      " [0.00357143 0.00357143 0.00357143 ... 0.00357143 0.00357143 0.00357143]]\n"
     ]
    }
   ],
   "source": [
    "data = fetch_20newsgroups(remove=('headers', 'footers', 'quotes')) # 使用remove去除正文以外的信息\n",
    "max_features = 1000 # 设置最大特征数\n",
    "tf_vectorizer = CountVectorizer(max_features=max_features, stop_words='english') # 创建CountVectorizer对象， max_features限制特征数，stop_words去除停用词，停用词意思是在文本处理中被忽略的常用词，这里设置english是使用了内置英文的停用词库\n",
    "tf = tf_vectorizer.fit_transform(data.data) # 将文本数据转换为词频矩阵\n",
    "n_topics = 20 # 设置主题数\n",
    "model = LatentDirichletAllocation(n_components=n_topics) # 创建LDA模型\n",
    "model.fit(tf) # 拟合模型\n",
    "print(model.components_)  # 各主题包含的单词的分布\n",
    "print(model.transform(tf))  # 使用主题描述的文本"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
